//
//  CardMatchingGame.m
//  MemoPocker
//
//  Created by Jose Luis Ferreyra on 20/02/13.
//  Copyright (c) 2013 Dharma. All rights reserved.
//

#import "CardMatchingGame.h"

@interface CardMatchingGame()
@property (readwrite, nonatomic) int score;
@property (nonatomic) NSUInteger numberOfCardFliped;
@property (strong, nonatomic) NSMutableArray *cards;
@end

#define MATCH_BONUS 4
#define MISMATCH_PENALTY 2
#define FLIP_COST 1
#define MAX_CARD_FLIPED 2

@implementation CardMatchingGame

//lazy instantiation
- (NSMutableArray *) cards{
    if (!_cards) _cards =[[NSMutableArray alloc] init];
    return _cards;
}

-(id)initWithCardCount: (NSUInteger)count
             usingDeck:(Deck *)deck{
    self = [super init];
    
    if (self)
    {
        for (int i=0; i<count; i++)
        {
            Card *card = [deck drawRandomCard];
            if (card)
            {
                self.cards[i] = card;
            }
            else
            {
                self = nil;
                break;
            }
        }
    }
    return self;
}

- (Card *)cardAtIndex:(NSUInteger)index
{
    return (index < [self.cards count]) ? self.cards[index] : nil;
}

- (void) resetFacedUpCards{
    for (Card *otherCard in self.cards) {
        if (otherCard.isFaceUp && !otherCard.isUnplayable) {
            otherCard.faceUp=NO;
            self.numberOfCardFliped--;
        }
    }
}


- (void) flipCardAtIndex:(NSUInteger)index
{
    if (self.numberOfCardFliped>=MAX_CARD_FLIPED){
        [self resetFacedUpCards];
    }
    Card *card = [self cardAtIndex:index];
    if (!card.isFaceUp){
        for (Card *otherCard in self.cards) {
            if (otherCard.isFaceUp && !otherCard.isUnplayable) {
                int matchScore = [card match:@[otherCard]];
                if (matchScore){
                    self.score += matchScore * MATCH_BONUS;
                    card.unplayable = YES;
                    otherCard.unplayable = YES;
                    self.numberOfCardFliped-=2;
                }
                else
                {
                    self.score -= MISMATCH_PENALTY;
                }
            }
        }
        self.score -= FLIP_COST;
        self.numberOfCardFliped++;
    }
    if (card.isFaceUp){
        self.numberOfCardFliped--;
    }
    card.faceUp = !card.isFaceUp;
}



@end
